import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))

import requests
import json
from reqapi.api import BaseApi,ApiConfig

class QueryBatchOrderApi(BaseApi):
    def execute(self, order_no, version=""):
        """
        查询批量订单信息API
        
        Args:
            order_no: 订单号
            version: APP版本号，默认"5.28.2"
            
        Returns:
            dict: 包含以下字段的字典：
                - batchOrderNo: 批量订单号
                - orderNo: 订单号
                - totalNumber: 总数量
                - successNumber: 成功数量
                - failNumber: 失败数量
                - failStatus: 失败状态
                - failReasons: 失败原因
                - successList: 成功列表
                - autoSendTradeOffer: 是否自动发送交易报价
                - deliveryStrategyType: 发货策略类型
        """
        url = f"{self.BASE_URL}/api/youpin/bff/trade/v1/order/batch/sell/queryBatchOrderInfo"
        data = {
            "orderNo": order_no,
            "version": ApiConfig.APP_VERSION,
            "Sessionid": self.device_id
        }
        headers = self.common_headers.copy()
        print("\n=== 请求信息 ===")
        print(f"请求URL: {url}")
        print(f"请求方法: POST")
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        print(f"请求数据: {json.dumps(data, indent=2, ensure_ascii=False)}")
        try:
            response = self.interceptor.send_request(url, json=data, headers=headers, need_encrypt=False)
            print("\n=== 响应信息 ===")
            if isinstance(response, dict):
                result = response
            elif hasattr(response, 'json'):
                result = response.json()
            else:
                result = response
            print(f"响应数据: {json.dumps(result, indent=2, ensure_ascii=False)}")
            if result.get('code') != 0:
                print(f"API返回错误: {result.get('msg', '未知错误')}")
                return None
            data = result.get('data', {})
            return {
                'batchOrderNo': data.get('batchOrderNo'),
                'orderNo': data.get('orderNo'),
                'totalNumber': data.get('totalNumber'),
                'successNumber': data.get('successNumber'),
                'failNumber': data.get('failNumber'),
                'failStatus': data.get('failStatus'),
                'failReasons': data.get('failReasons'),
                'successList': data.get('successList'),
                'autoSendTradeOffer': data.get('autoSendTradeOffer', False),
                'deliveryStrategyType': data.get('deliveryStrategyType')
            }
        except Exception as e:
            print(f"请求发生错误: {str(e)}")
            return None


def main():
    """测试批量订单查询API"""
    try:
        # 使用实际的认证信息
        from com.db.order_account_manager import OrderAccountManager
        account_manager = OrderAccountManager()
        account = account_manager.get_account_by_id(1)
        
        if not account:
            print("无法获取ID为1的账号")
            return
        
        device_id = account.get('device_id', '')
        auth_token = account.get('uu_token', '')
        uk = account.get('uk', '')
        
        # 创建API实例
        api = QueryBatchOrderApi(
            device_token=device_id,  # 使用 device_id 作为 device_token
            device_id=device_id,
            auth_token=auth_token,
            uk=uk
        )
        
        # 调用API
        result = api.execute(
            order_no="2025020210964679356",
            version="5.28.2"
        )
        
        # 打印结果
        print("\n=== 批量订单查询结果 ===")
        if result is None:
            print("批量订单查询失败，可能是登录信息失效或接口返回错误。")
        else:
            print(f"总数量: {result['totalNumber']}")
            if result['successNumber'] is not None:
                print(f"成功数量: {result['successNumber']}")
            if result['failNumber'] is not None:
                print(f"失败数量: {result['failNumber']}")
            if result['failStatus'] is not None:
                print(f"失败状态: {result['failStatus']}")
            if result['failReasons']:
                print(f"失败原因: {result['failReasons']}")
            if result['successList']:
                print(f"成功列表: {result['successList']}")
            print(f"自动发送交易报价: {'是' if result['autoSendTradeOffer'] else '否'}")
            print(f"发货策略类型: {result['deliveryStrategyType']}")
    except Exception as e:
        print(f"测试失败: {str(e)}")


if __name__ == "__main__":
    main()
